package com.jordi.tetris.model;

public class TetrisGame extends Observable {

	private Board gameBoard;
	private int points;
	private int level;

	public TetrisGame() {
		this.gameBoard = new Board();
		this.points = 0;
		this.level = 0;
	}

	public void startGame() {
	}

	public boolean isGameOver() {
		return gameBoard.isAnyColumnFull();
	}

	public int getCurrentPoints() {
		return points;
	}

	public int getCurrentLevel() {
		return level;
	}

	public void leftMoveHandler() {
		if (gameBoard.canMovePieceLeft()) {
			gameBoard.leftPiece();
			notifyObservers();
		}
	}

	public void rightMoveHandler() {
		if (gameBoard.canMovePieceRight()) {
			gameBoard.rightPiece();
			notifyObservers();
		}
	}

	public void downMoveHandler() {
		if (gameBoard.canMovePieceDown()) {
			gameBoard.downPiece();
		} else {
			gameBoard.mergePieceToBoard();
			addPoints();
		}
		notifyObservers();
	}

	public void leftMoveHandler(int moves) {
		for (int i = 0; i < moves; i++) {
			if (gameBoard.canMovePieceLeft())
				gameBoard.leftPiece();
			else
				break;
		}
		notifyObservers();
	}

	public void rightMoveHandler(int moves) {
		for (int i = 0; i < moves; i++) {
			if (gameBoard.canMovePieceRight())
				gameBoard.rightPiece();
			else
				break;
		}
		notifyObservers();
	}

	public void downMoveHandler(int moves) {
		for (int i = 0; i < moves; i++) {
			if (gameBoard.canMovePieceDown()) {
				gameBoard.downPiece();
			} else {
				gameBoard.mergePieceToBoard();
				addPoints();
				break;
			}
		}
		notifyObservers();
	}

	public void rotatePiece() {
		gameBoard.rotatePiece();
	}

	public Board getGameBoard() {
		return gameBoard;
	}

	public void update() {
		if (gameBoard.canMovePieceDown()) {
			gameBoard.downPiece();
		} else {
			gameBoard.mergePieceToBoard();
			addPoints();
		}
		notifyObservers();
	}

	private void addPoints() {
		points += gameBoard.cleanFullRows();
	}

}
